package com.qf.commons.core.utils;


import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.UUID;


public class JwtUtils {
    //密钥由调用方来决定
    private static String secretKey = "cb5e8c37-7489-4cff-9631-d765e3800eb6";
    //有效期也由调用方来决定
    private static long ttl = 2 * 60 * 60 * 1000 ;
//    private static long ttl = 20 * 1000 ;

    public static String createJwtToken(Long uid){
        long now = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder()
                .claim("uid",uid)
                .setIssuedAt(new Date(now))
                .signWith(SignatureAlgorithm.HS256,secretKey);
        if(ttl > 0){
            jwtBuilder.setExpiration(new Date(now+ttl));
        }
        return jwtBuilder.compact();
    }
    public static Long parseJwtToken(String jwtToken){
        try {
            return Long.valueOf((int) Jwts.parser().setSigningKey(secretKey)
                    .parseClaimsJws(jwtToken).getBody().get("uid"));
        }catch (Exception e) {
            return null;
        }

    }

    public static void main(String[] args) {
//        String jwtToken = JwtUtils.createJwtToken(500l);
//        System.out.println(jwtToken);
        //System.out.println(UUID.randomUUID().toString());
        //Long uid = parseJwtToken("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhYmMiLCJzdWIiOiLmoIfpopgiLCJpYXQiOjE2NTcwMDU3OTIsImV4cCI6MTY1NzAxMjk5Mn0.PD5__YT3t72aH8HYbWzES8tiY7uGBpgy7E3GvcDbVl4");

        Long nickname =  JwtUtils.parseJwtToken("eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjUwMCwiaWF0IjoxNjU3MDE4OTQ1LCJleHAiOjE2NTcwMTkxNDV9.cdOaL2D6L1wqqK2ieQd1fHbr1Gktai2CmOeBX3eoO9I");
        System.out.println(nickname);

    }
}
